//
//  GoodsPostersShareView.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/11/20.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "GoodsPostersShareView.h"

@implementation GoodsPostersShareView
extern UserModel *userModel;


- (void)awakeFromNib {
    
    [super awakeFromNib];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelView)];
    [self.deleteImageView addGestureRecognizer:tap];
    
    self.iconImageW.constant = RATIO_HEIGHT* 260;
    self.iconImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.iconImageView.clipsToBounds = YES;
    self.nameLabel.font = kPMFont(18*RATIOFont_HEIGHT);
    self.contentLabel.font = kPMFont(14*RATIOFont_HEIGHT);
    
    NSString *data = [self getShareURL];
    if (self.dataString.length >  0) {
        data = self.dataString;
    }
    self.codeImageView.image = [SGQRCodeObtain generateQRCodeWithData:data size:210 logoImage:[UIImage imageNamed:@"logo2"] ratio:0.2];
    self.bgView.layer.cornerRadius = 5;
    self.bgView.clipsToBounds = YES;
    
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,KSCREEN_WIDTH,58);
    gl.startPoint = CGPointMake(0.22, 0.36);
    gl.endPoint = CGPointMake(0.85, 0.72);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:221/255.0 green:169/255.0 blue:72/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:189/255.0 green:135/255.0 blue:35/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    
    [self.priceBgView.layer insertSublayer:gl atIndex:0];

    
    CAGradientLayer *gl1 = [CAGradientLayer layer];
    gl1.frame = CGRectMake(0,0,KSCREEN_WIDTH,58);
    gl1.startPoint = CGPointMake(0, 0.31);
    gl1.endPoint = CGPointMake(0.93, 0.42);
    gl1.colors = @[(__bridge id)[UIColor colorWithRed:225/255.0 green:174/255.0 blue:8/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:44/255.0 blue:2/255.0 alpha:1.0].CGColor];
    gl1.locations = @[@(0), @(1.0f)];
    [self.aBulkBgView.layer insertSublayer:gl1 atIndex:0];
    
    CAGradientLayer *gl2 = [CAGradientLayer layer];
    gl2.frame = CGRectMake(0,0,KSCREEN_WIDTH,58);
    gl2.startPoint = CGPointMake(0.22, 0.36);
    gl2.endPoint = CGPointMake(0.85, 0.72);
    gl2.colors = @[(__bridge id)[UIColor colorWithRed:221/255.0 green:169/255.0 blue:72/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:189/255.0 green:135/255.0 blue:35/255.0 alpha:1.0].CGColor];
    gl2.locations = @[@(0), @(1.0f)];
    [self.startAbulkBgView.layer insertSublayer:gl2 atIndex:0];
    
    
}

+ (instancetype)showView
{
    UIWindow *window = UIApplication.sharedApplication.keyWindow;

    GoodsPostersShareView *view = [[NSBundle mainBundle] loadNibNamed:@"GoodsPostersShareView" owner:self options:nil].lastObject;
    view.frame = window.bounds;
    view.backgroundColor =  [[UIColor blackColor] colorWithAlphaComponent:0.7];
    view.deleteImageView.alpha = 1;
    
    [window addSubview:view];

    
    
    return view;
}

- (void)cancelView {
    
    [UIView animateWithDuration:0.5 animations:^{
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)tap {
    
    
}
- (IBAction)saveImgClick:(id)sender {
    
    //UIGraphicsBeginImageContext(self.bgView.bounds.size);     //currentView 当前的view  创建一个基于绘图的图形上下文并指定大小为当前视图的bounds
    UIGraphicsBeginImageContextWithOptions(self.bgView.bounds.size, NO, 0.0);


    [self.bgView.layer renderInContext:UIGraphicsGetCurrentContext()];//renderInContext呈现接受者及其子范围到指定的上下文
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();//返回一个基于当前图形上下文的图片
    UIGraphicsEndImageContext();//移除栈顶的基于当前位图的图形上下文
    UIImageWriteToSavedPhotosAlbum(viewImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);//然后将该图片保存到图片图
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error  contextInfo:(void *)contextInfo{

 if (error) {

        [SVProgressHUD showErrorWithStatus:@"保存失败"];

    }else{

        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        [self cancelView];
    }

}


- (void)setDataString:(NSString *)dataString {
    
    _dataString = dataString;
    self.codeImageView.image = [SGQRCodeObtain generateQRCodeWithData:dataString size:210 logoImage:[UIImage imageNamed:@"logo2"] ratio:0.2];
    self.bgView.layer.cornerRadius = 5;
    self.bgView.clipsToBounds = YES;
    
    
    
}

- (NSString *)getShareURL {
    
    
    NSString *userCode= @"";
    if ([CommonTTool isStrNull:userModel.my_code]) {
        userCode = @"";
    }else {
        userCode = [NSString stringWithFormat:@"?code=%@",userModel.my_code];
    }
    
    return [NSString stringWithFormat:@"%@%@",SHARE_HOME_URL,userCode];
    
}

- (void)setModel:(MailGoodsDetailsModel *)model {
    
    _model = model;
    if (![CommonTTool isStrNull:model.banner_list]) {
        SD_SETIMAGE_PlaceHolder(self.iconImageView, model.banner_list[0][@"path"], @"default_image_square");
    }
    self.nameLabel.text = model.sku_name;
    self.contentLabel.text  = model.att_title;
    if (model.is_pt == 2 && model.sku_type == 1) {
        self.aBulkBgView.hidden = YES;
        self.startAbulkBgView.hidden = NO;
        self.priceBgView.hidden = YES;
        [self setStartTg];
    }else if (model.sku_type == 2 || model.sku_type == 9) {
        self.aBulkBgView.hidden = NO;
        self.startAbulkBgView.hidden = YES;
        self.priceBgView.hidden =YES;
        [self setAbulkContent];
    }else {
        self.aBulkBgView.hidden = YES;
        self.startAbulkBgView.hidden = YES;
        self.priceBgView.hidden =NO;
        [self setPriceContent];
    }
    
    
    
}

#pragma mark - 团购商品设置
- (void)setAbulkContent {
    
    self.twoTgPriceLabel.text = [CommonTTool getPrice:self.model.buy_price];
    self.twoStockLabel.text = [NSString stringWithFormat:@" 仅剩%d件 ",self.model.stock];
    UIColor *color= [UIColor blackColor];
    self.twoStockLabel.backgroundColor  = [color colorWithAlphaComponent:0.4];

    NSString *price = [NSString stringWithFormat:@"销售价¥%@",[CommonTTool getPrice:self.model.market_price]];
       NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:price];
       [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, attri.length)];
       [attri addAttribute:NSStrikethroughColorAttributeName value: self.onePriceLabel.textColor range:NSMakeRange(0, attri.length)];
    self.twoPriceLabel.attributedText = attri;
    
    NSString *deadlineStr = self.model.end_time;
    // 倒计时的时间 测试数据
//    NSString *deadlineStr = @"2020-06-24 12:00:00";
    // 当前时间的时间戳
    NSString *nowStr = [CommonTTool getCurrentTimeyyyymmdd];
    // 计算时间差值
    NSInteger secondsCountDown = [CommonTTool getDateDifferenceWithNowDateStr:nowStr deadlineStr:deadlineStr];
    if (secondsCountDown <= 0) {
        [self setAbulkEndInfo];
        return;
    }
    
    
    
    __weak __typeof(self) weakSelf = self;
    if (_timer == nil) {
        __block NSInteger timeout = secondsCountDown; // 倒计时时间
        
        if (timeout!=0) {
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
            dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC,  0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout <= 0){ //  当倒计时结束时做需要的操作: 关闭 活动到期不能提交
                    dispatch_source_cancel(self->_timer);
                    self->_timer = nil;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self setAbulkEndInfo];
                        [[NSNotificationCenter defaultCenter] postNotificationName:kUserAbulkDetailsUpDate object:nil];
                    });
                } else { // 倒计时重新计算 时/分/秒
                    NSInteger days = (int)(timeout/(3600*24));
                    NSInteger hours = (int)((timeout-days*24*3600)/3600);
                    NSInteger minute = (int)(timeout-days*24*3600-hours*3600)/60;
                    NSInteger second = timeout - days*24*3600 - hours*3600 - minute*60;
                    //NSString *strTime = [NSString stringWithFormat:@" %ld小时%ld分钟 ", hours, minute];
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        if (days == 0) {
//                            weakSelf.timeTwoLabel.text = strTime;
//                        } else {
//                            weakSelf.timeTwoLabel.text = [NSString stringWithFormat:@" %ld天%ld小时%ld分钟 ", days, hours, minute];
//                        }
                        weakSelf.twoDayLabel.text = [NSString stringWithFormat:@"%ld",days];
                        weakSelf.twoHoursLabel.text = [NSString stringWithFormat:@"%02ld",hours];
                        weakSelf.twoMinutesLabel.text = [NSString stringWithFormat:@"%02ld",minute];
                        weakSelf.twoSecondsLabel.text = [NSString stringWithFormat:@"%02ld",second];
                        
                    });
                    timeout--; // 递减 倒计时-1(总时间以秒来计算)
                }
            });
            dispatch_resume(_timer);
        }
    }
    
    
}

- (void)setAbulkEndInfo {
    
    self.twoDayLabel.hidden = YES;
    self.twoHoursLabel.hidden = YES;
    self.twoMinutesLabel.hidden = YES;
    self.twoDayLabel.hidden = YES;
    self.twoSecondsLabel.hidden = YES;
    self.twoOneLabel.hidden = YES;
    self.twoTwoLabel.hidden = YES;
    self.twoThreeLabel.hidden = YES;
    self.twoEndTimeLabel.hidden = NO;
}

#pragma mark - 普通商品设置
- (void)setPriceContent {
    
   
    if (self.model.is_yk == 2) {
        self.onePriceInfoLabel.text = @"银卡会员价";
        self.oneVipPriceLabel.text = [CommonTTool getPrice:self.model.yk_price];
           NSString *price = [NSString stringWithFormat:@"销售价¥%@",[CommonTTool getPrice:self.model.market_price]];
           NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:price];
           [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, attri.length)];
           [attri addAttribute:NSStrikethroughColorAttributeName value: self.onePriceLabel.textColor range:NSMakeRange(0, attri.length)];
           self.onePriceLabel.attributedText = attri;
    }else {
        self.onePriceInfoLabel.text = @"会员补贴价";
        self.oneVipPriceLabel.text = [CommonTTool getPrice:self.model.vip_price];
           NSString *price = [NSString stringWithFormat:@"销售价¥%@",[CommonTTool getPrice:self.model.market_price]];
           NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:price];
           [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, attri.length)];
           [attri addAttribute:NSStrikethroughColorAttributeName value: self.onePriceLabel.textColor range:NSMakeRange(0, attri.length)];
           self.onePriceLabel.attributedText = attri;
    }
}

#pragma mark - 团购商品设置
- (void)setStartTg {
    
    self.threePriceLabel.text = [CommonTTool  getPrice:self.model.pt_price];
    self.threeStatrNumberLabel.text = [NSString stringWithFormat:@" %@ ",self.model.pt_ct_rs];
    // 倒计时的时间 测试数据
    NSString *deadlineStr = [NSString stringWithFormat:@"%@",self.model.pt_end_time];
    if (self.model.pt_end_time.length < 11) {
        deadlineStr = [NSString stringWithFormat:@"%@ 23:59:00",self.model.pt_end_time];
    }
    
    // 当前时间的时间戳
    NSString *nowStr = [CommonTTool getCurrentTimeyyyymmdd];
    // 计算时间差值
    NSInteger timeout = [CommonTTool getDateDifferenceWithNowDateStr:nowStr deadlineStr:deadlineStr];
    NSInteger days = (int)(timeout/(3600*24));
    NSInteger hours = (int)((timeout-days*24*3600)/3600);
    if (days == 0) {
        self.threeTimerLabel.text = [NSString stringWithFormat:@"   %ld小时后优惠结束 ",(long)hours];
        self.threeTimeLookLabel.text = [NSString stringWithFormat:@"   %ld小时后优惠结束 ",(long)hours];
    }else {
        self.threeTimerLabel.text = [NSString stringWithFormat:@"   %ld天%ld小时后优惠结束 ",days,(long)hours];
        self.threeTimeLookLabel.text = [NSString stringWithFormat:@"   %ld天%ld小时后优惠结束 ",days,(long)hours];
    }

    
    self.threeStartLabel.layer.borderWidth = 0.5;
    self.threeStartLabel.layer.borderColor = WhiteColor.CGColor;
    
    
}


@end
